// 此模块存储渲染左侧栏菜单数据、选项卡列表及当前选项卡数据，需要做持久化处理
export default {
	namespaced: true,
	state: () => {
		return {
			menus: [], // 渲染左侧栏菜单的数据
			isCollapse: false,  // 左侧菜单栏是否折叠
			taglist: [], // 渲染选项卡数据
			currenttag: null // 当前被激活的选项卡
		}
	},
	getters: {
		// 面包屑
		breads: state => {
			let breadList = [];
			if (state.currenttag) {
				breadList = [...state.currenttag.parentsInfo];
				breadList.push({
					id: state.currenttag.id,
					label: state.currenttag.label
				});
			}
			return breadList;
		},
		menuRoutes: state => {
			const routes = [];
			const transData = (menus) => {
				menus.forEach(menu => {
					if (menu.children && menu.children.length > 0) {
						transData(menu.children);
					} else {
						routes.push({
							path: menu.path,
							name: menu.name,
							url: `${menu.url}.vue`
						});
					}
				})
			}
			transData(state.menus);
			return routes;
		}
	},
	mutations: {
		initMenus(state, { menus, path }){
			const transData = (menus, arr) => {
				menus.forEach(item => {
					const parentsInfo = arr ? [...arr] : [];
					if (item.children && item.children.length > 0) {
						parentsInfo.push({
							id: item.id,
							label: item.label,
						});
						transData(item.children, parentsInfo);
					} else {
						item.parentsInfo = parentsInfo;
					}
				});
			}
			transData(menus);
			state.menus = menus;
			let homeTag = menus.find(menu => {
				console.log(menu.path,path);
				return menu.path === path;
			});
			console.log(homeTag);
			this.commit('pannel/initTaglist', homeTag);
		},
		collapseMenu(state) {
			state.isCollapse = !state.isCollapse;
		},
		initTaglist(state, curr) {
			let index = state.taglist.findIndex(tag => {
				return tag.id === curr.id;
			});
			if (index === -1) {
				state.taglist.push(curr);
			}
			state.currenttag = curr;
		},
		delTagItem(state, {index}) {
			let len = state.taglist.length - 1;
			state.taglist.splice(index, 1);
			if (index === len) {
				state.currenttag = state.taglist[index - 1];
			} else {
				state.currenttag = state.taglist[index];
			}
		}
	}
}